package com.fzdy.dataplatform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzdy.dataplatform.controller.api.ModuleCallback;
import com.fzdy.dataplatform.controller.api.pwd.ChangePwdApi;
import com.fzdy.dataplatform.controller.api.right.ButtonApi;
import com.fzdy.dataplatform.controller.api.right.MenuApi;
import com.fzdy.dataplatform.controller.api.sysLog.LogStringUtil;
import com.fzdy.dataplatform.controller.api.sysLog.SysLogApi;
import com.fzdy.dataplatform.controller.api.user.UserListApi;
import com.fzdy.dataplatform.core.common.AjaxCallback;
import com.fzdy.dataplatform.core.common.Check;
import com.fzdy.dataplatform.core.common.TimeStampTool;
import com.fzdy.dataplatform.core.controller.BaseController;
import com.fzdy.dataplatform.entity.Module;
import com.fzdy.dataplatform.entity.Right;
import com.fzdy.dataplatform.entity.User;
import com.fzdy.dataplatform.login.UserApi;
import com.fzdy.dataplatform.service.ModuleService;
import com.fzdy.dataplatform.service.RightService;
import com.fzdy.dataplatform.service.UserService;
import com.fzdy.dataplatform.webutil.AllModule;
import com.fzdy.dataplatform.webutil.LoginUserInfo;
import com.fzdy.dataplatform.webutil.MD5ArithmeticUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "/sysmanage/account")
public class AccountController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;
    @Autowired
    private RightService rightService;



    @RequestMapping("/userLogin")
    @ResponseBody
    public String userLogin(@RequestBody UserApi userApi, HttpServletRequest request) {
        //检查是否加载了所有的权限到AllModule
        checkRight();
        //返回值
        AjaxCallback ajaxCallback;


        SysLogApi log_sysLogApi=new SysLogApi();
        log_sysLogApi.setOperation(LogStringUtil.LOGIN);
        log_sysLogApi.setModule(LogStringUtil.ACCOUNT);
        JSONObject log_content=new JSONObject();
        //输入验证
        if (Check.checkStringNull(userApi.getUsercode())) {
            ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "用户名不能为空");
            log_sysLogApi.setStatus(LogStringUtil.FAILURE);
            log_content.put("账号","空");
            log_content.put("失败原因","用户名不能为空");
        }else {
            if (Check.checkStringNull(userApi.getPwd())) {
                ajaxCallback = new AjaxCallback("301", "密码不能为空");
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                log_content.put("账号",userApi.getUsercode());
                log_content.put("失败原因","密码不能为空");
            }else {
                //到数据库去查找用户名密码对应账户
                User loginUser = new User(userApi.getUsercode(), MD5ArithmeticUtils.getMd5(userApi.getPwd()));
                loginUser.setStatus(1);
                List<User> list = userService.findByExampleEq(loginUser);
                //找不到返回"账号或密码错误"
                if (list.size() < 1) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "账号或密码错误");
                    log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                    log_content.put("账号",userApi.getUsercode());
                    log_content.put("失败原因","账号或密码错误");
                }else {
                    ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "登录成功");
                    //将登录的人的信息对应放入WebUtilify
                    loginUser = list.get(0);
                    log_sysLogApi.setStatus(LogStringUtil.SUCCESS);
                    log_content.put("账号",userApi.getUsercode());
                    log_content.put("用户名",loginUser.getName());
                    log_sysLogApi.setOpreatorid(loginUser.getId());
                    String apikey = MD5ArithmeticUtils.getMd5(loginUser.getAccount() +
                            TimeStampTool.DateToString("HH:mm:ss", new Date()));
                    UserListApi api = new UserListApi();
                    api.setId(loginUser.getId());
                    api.setUname(loginUser.getName());
                    if (loginUser.getRole().getIsAdmin() == 1) {
                        LoginUserInfo loginUserInfo = new LoginUserInfo();
                        loginUserInfo.setAdmin(true);
                        loginUserInfo.setApikey(apikey);
                        loginUserInfo.setUser(loginUser);
                        webUtilify.putLoginInfo(apikey, loginUserInfo);
                        api.setRole(loginUser.getRole().getName());
                    } else {
                        LoginUserInfo loginUserInfo = new LoginUserInfo();
                        loginUserInfo.setAdmin(false);
                        loginUserInfo.setApikey(apikey);
                        loginUserInfo.setUser(loginUser);
                        //将登录的人的权限id放入WebUtilify,管理员不需要权限
                        Right right = new Right();
                        right.setRoid(loginUser.getRoid());
                        List<Right> rights = rightService.findByExampleEq(right);
                        int[] ringtIds = new int[rights.size()];
                        for (int i = 0; i < rights.size(); i++) {
                            ringtIds[i] = rights.get(i).getModuleid();
                        }
                        loginUserInfo.setRingtIds(ringtIds);
                        webUtilify.putLoginInfo(apikey, loginUserInfo);
                    }

                    ajaxCallback.setData(api);
                    ajaxCallback.setApikey(apikey);
                }
            }
        }
        log_sysLogApi.setContent(log_content);
        syslogService.WriteLog(log_sysLogApi);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/LoginError")
    @ResponseBody
    public String LoginError(HttpServletRequest request) {
        AjaxCallback ajaxCallback = new AjaxCallback("301", "您没有对应的权限");
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/changePassword")
    @ResponseBody
    public String ChangePassword(HttpServletRequest request, @RequestBody ChangePwdApi changePwdApi) {
        User user = webUtilify.LoginUserinfo(request);
        SysLogApi log_sysLogApi=new SysLogApi();
        log_sysLogApi.setOperation(LogStringUtil.UPDATA);
        log_sysLogApi.setModule(LogStringUtil.CHANGEPWD);
        log_sysLogApi.setOpreatorid(user.getId());
        JSONObject log_content=new JSONObject();
        AjaxCallback ajaxCallback;
        if (Check.checkStringNull(changePwdApi.getOldPassword())) {
            ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "原密码不能为空");
            log_sysLogApi.setStatus(LogStringUtil.FAILURE);
            log_content.put("失败原因","原密码不能为空");
        }else {
            if (Check.checkStringNull(changePwdApi.getNewPassword())) {
                ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "新密码不能为空");
                log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                log_content.put("失败原因","新密码不能为空");
            }else {
                if (Check.checkStringNull(changePwdApi.getNewPassword2()) || !changePwdApi.getNewPassword2()
                        .equals(changePwdApi.getNewPassword())) {
                    ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "两次密码不一致");
                    log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                    log_content.put("失败原因","两次密码不一致");
                }else {
                    if (!MD5ArithmeticUtils.getMd5(changePwdApi.getOldPassword()).equals(user.getPwd())) {
                        ajaxCallback = new AjaxCallback(ModuleCallback.FAILURENO, "原密码错误");
                        log_sysLogApi.setStatus(LogStringUtil.FAILURE);
                        log_content.put("失败原因","原密码错误");
                    }else {
                        user = userService.get(user.getId());
                        user.setPwd(MD5ArithmeticUtils.getMd5(changePwdApi.getNewPassword()));
                        userService.updateT(user);
                        webUtilify.delByUserid(user.getId());
                        ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "修改成功");
                        log_sysLogApi.setStatus(LogStringUtil.SUCCESS);
                    }
                }
            }
        }
        log_sysLogApi.setContent(log_content);
        syslogService.WriteLog(log_sysLogApi);
        return JSON.toJSONString(ajaxCallback);
    }

    @RequestMapping(value = "/getuserMenu")
    @ResponseBody
    public String getuserMenu(HttpServletRequest request) {
        List<Right> rights;
        if (webUtilify.isAdmin(request)) {
            rights = rightService.getList();
        } else {
            Right right = new Right();
            right.setRoid(webUtilify.LoginUserinfo(request).getRoid());
            rights = rightService.findByExampleEq(right);
        }
        return JSON.toJSONString(rightSort(rights));
    }


    @RequestMapping(value = "/loginOut")
    @ResponseBody
    public String loginOut(HttpServletRequest request) {
        webUtilify.delLoginInfo(request);
        AjaxCallback ajaxCallback = new AjaxCallback(ModuleCallback.SUCCESSNO, "退出成功");
        return JSON.toJSONString(ajaxCallback);
    }


    private ModuleCallback rightSort(List<Right> rights) {
        int maxIndex = 0;
        List<ButtonApi> buttonList = new ArrayList<>();
        List<MenuApi> menuList = new ArrayList<>();
        Map<Integer, MenuApi> menuApiMap = new HashMap<>();
        List<MenuApi> children = new ArrayList<>();
        for (Right right : rights) {
            if (right.getModule().getType() == 1) {
                ButtonApi buttonApi = new ButtonApi(right.getModuleid(), right.getModule().getPid(), right.getModule().getName());
                buttonList.add(buttonApi);
            } else if (right.getModule().getType() == 0) {
                MenuApi menuApi = new MenuApi();
                menuApi.setIcon(right.getModule().getIcon());
                menuApi.setId(right.getModule().getNavtabid());
                menuApi.setIndex(right.getModule().getSeq());
                menuApi.setName(right.getModule().getName());
                menuApi.setTid(right.getModuleid());
                menuApi.setUrl(right.getModule().getUrl());

                if (right.getModule().getPid() != null) {
                    menuApi.setPid(right.getModule().getPid());
                    children.add(menuApi);
                } else {
                    menuApiMap.put(right.getModule().getSeq(), menuApi);
                    if (maxIndex < menuApi.getIndex()) {
                        maxIndex = menuApi.getIndex();
                    }
                }
            }
        }
        for (MenuApi child : children) {
            for (Integer parentIndex : menuApiMap.keySet()) {
                if (child.getPid().equals(menuApiMap.get(parentIndex).getTid())) {
                    if (menuApiMap.get(parentIndex).getChildren() == null) {
                        List<MenuApi> c = new ArrayList<>();
                        c.add(child);
                        menuApiMap.get(parentIndex).setChildren(c);
                    } else {
                        menuApiMap.get(parentIndex).getChildren().add(child);
                    }
                }
            }
        }
        for (int i = 0; i <= maxIndex; i++) {
            if (menuApiMap.get(i) != null) {
                menuList.add(menuApiMap.get(i));
            }
        }
        return new ModuleCallback(menuList, buttonList);
    }

    private void checkRight() {
        if (AllModule.allModule.size() == 0) {
            Map<String, Integer> allModule = new HashMap<>();
            List<Module> list = moduleService.getList();
            for (Module module : list) {
                allModule.put(module.getUrl(), module.getId());
            }
            AllModule.allModule = allModule;
        }
    }
}
